package ar.org.sstuyv


import org.springframework.dao.DataIntegrityViolationException
import grails.converters.JSON
import grails.plugins.springsecurity.Secured

@Secured(["hasRole('Admin')"])
class PartidoController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
		
		
				
		//listJSON(params)
        params.max = Math.min(max ?: 10, 100)
        [partidoInstanceList: Partido.list(params), partidoInstanceTotal: Partido.count()]
    }
	
	def listAdvancedJSON = {
		
//		def methods =['code', 'name', 'wonLeagues']
//		def dets = [] as Set
//		
//		//def metodos = Partido.metaClass.properties.findAll { p -> println "${p.name} = ${p.type}" }
//		def m = methods.each {name ->  Partido.metaClass.properties.findAll { name == it} }
//		m.each { print it }
		
		
		def sortIndex = params.sidx ?: 'nombe'
		def sortOrder  = params.sord ?: 'asc'
		def maxRows = Integer.valueOf(params.rows)
		def currentPage = Integer.valueOf(params.page) ?: 1
		def rowOffset = currentPage == 1 ? 0 : (currentPage - 1) * maxRows
		
		def Partidos = Partido.createCriteria().list(max: maxRows, offset: rowOffset) {
			//if (params.id) eq('id', params.id.toLong())
			//methods.eachWithIndex { method ->
				//if(params."$method") ilike(method, "%${params.$method}%")
				
				//print "%${params.$method}%"
			//}
			
			if (params.codigo) eq('codigo', params.codigo?.toInteger())
			if (params.nombre) ilike('partido', "%${params.nombre}%")
			if (params.codcatas) ilike('codcatas', "%${params.codcatas}%")
			order(sortIndex, sortOrder)
		}
		
		def totalRows = Partidos.totalCount
		def numberOfPages = Math.ceil(totalRows / maxRows)
		
		def results = Partidos?.collect {
			[
				 cell: [it.codigo, it.nombre, it.codcatas],
				 id: it.codigo
			]
		}

		
		def jsonData = [rows: results, page: currentPage, records: totalRows, total: numberOfPages]
		
		render jsonData as JSON
	}

    def create() {
        [partidoInstance: new Partido(params)]
    }

    def save() {
        def partidoInstance = new Partido(params)
        if (!partidoInstance.save(flush: true)) {
            render(view: "create", model: [partidoInstance: partidoInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'partido.label', default: 'Partido'), partidoInstance.id])
        redirect(action: "show", id: partidoInstance.id)
    }

    def show(Long id) {
        def partidoInstance = Partido.get(id)
        if (!partidoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'partido.label', default: 'Partido'), id])
            redirect(action: "list")
            return
        }

        [partidoInstance: partidoInstance]
    }

    def edit(Long id) {
        def partidoInstance = Partido.get(id)
        if (!partidoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'partido.label', default: 'Partido'), id])
            redirect(action: "list")
            return
        }

        [partidoInstance: partidoInstance]
    }

//    def update(Long id, Long version) {
//        def partidoInstance = Partido.get(id)
//        if (!partidoInstance) {
//            flash.message = message(code: 'default.not.found.message', args: [message(code: 'partido.label', default: 'Partido'), id])
//            redirect(action: "list")
//            return
//        }
//
//        if (version != null) {
//            if (partidoInstance.version > version) {
//                partidoInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
//                          [message(code: 'partido.label', default: 'Partido')] as Object[],
//                          "Another user has updated this Partido while you were editing")
//                render(view: "edit", model: [partidoInstance: partidoInstance])
//                return
//            }
//        }
//
//        partidoInstance.properties = params
//
//        if (!partidoInstance.save(flush: true)) {
//            render(view: "edit", model: [partidoInstance: partidoInstance])
//            return
//        }
//
//        flash.message = message(code: 'default.updated.message', args: [message(code: 'partido.label', default: 'Partido'), partidoInstance.id])
//        redirect(action: "show", id: partidoInstance.id)
//    }

	    def delete(Long id) {
        def partidoInstance = Partido.get(id)
        if (!partidoInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'partido.label', default: 'Partido'), id])
            redirect(action: "list")
            return
        }

        try {
            partidoInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'partido.label', default: 'Partido'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'partido.label', default: 'Partido'), id])
            redirect(action: "show", id: id)
        }
    }

		def update = {
			def teamInstance = Partido.get(params.id)
			if (teamInstance) {
				if (params.version) {
					def version = params.version.toLong()
					if (teamInstance.version > version) {
						render "error"
					}
				}
				teamInstance.properties = params
				if (!teamInstance.hasErrors() && teamInstance.save(flush: true)) {
					render "success"
				}
				else {
					render "error"
				}
			}
			else {
				render "error"
			}
		}
	
		
	def listJson = {
		
		def lst = Partido.findAll()
		
			StringBuffer buf = new StringBuffer("<select>")
			buf.append("<option value=\"${-1}\">")
			buf.append("")
			lst.each{
				buf.append("<option value=\"${it.id}\">")
				buf.append(it.toString())
				buf.append("</option>")
			}
			buf.append("</select>")
		
			render buf.toString()
	}
}
